﻿//using ET.DBCommon.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
//using ET.DBCommon.Model;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
//using ET.DBCommon.Enum;
using System.Threading;
using ET_DbCommon.Model;
using ET_DbCommon.DAL;
using ET_DbCommon.Enum;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// TestQuestionTaskEdit.xaml 的交互逻辑
    /// </summary>
    public partial class TestQuestionTaskEdit : Window, INotifyPropertyChanged
    {
        public TestQuestionTaskViewModel viewModel { get; set; }
        public TestQuestionViewModel viewModelQuestion { get; set; }
        public ObservableCollection<PublicParameter> DevStateList { get; set; } = new ObservableCollection<PublicParameter>();
        public ObservableCollection<TrainPositionParameter> TrainPositionList { get; set; } = new ObservableCollection<TrainPositionParameter>();
        public ObservableCollection<BeforeStepParameter> BeforeList { get; set; } = new ObservableCollection<BeforeStepParameter>();
        public ObservableCollection<TestQuestionTaskViewModel> TestQuestionTaskList { get; set; } = new ObservableCollection<TestQuestionTaskViewModel>();

        public bool IsSelected = false;//指示搜索框功能是否开启
        Task select;
        ListenToFuzzyQueryVoid fuzzyQuery;//任务筛选类
        CancellationTokenSource tokenSource;
        CancellationToken cancellationToken;//取消筛选任务线程
        List<TestQuestionTaskViewModel> tempTaskList = new List<TestQuestionTaskViewModel>();
        #region DicDevType
        private Dictionary<int, string> m_DicDevType;

        public Dictionary<int, string> DicDevType
        {
            get
            {
                return this.m_DicDevType;
            }
            set
            {
                this.m_DicDevType = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        public List<DeviceModel> TrainList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.列车];
        public List<DeviceModel> AreaList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.计轴区段];
        public List<Paper_TestQuestion_Task_StepModel> BeforeStepList { get; set; }

        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        #endregion

        public bool IsLook { get; set; }

        public TestQuestionTaskEdit(TestQuestionTaskViewModel _viewModel, TestQuestionViewModel _viewModelQuestion, bool _isLook = false)
        {
            InitializeComponent();
            this.viewModel = _viewModel;
            this.viewModelQuestion = _viewModelQuestion;
            this.IsLook = _isLook;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            Dictionary<string, bool> dicTrainPosition = new Dictionary<string, bool>();
            foreach (var param in this.TrainPositionList)
            {
                if (param.DevTrainID == 0 || param.DevAreaID == 0) continue;
                dicTrainPosition.Add(param.DevTrainID + "|" + param.DevAreaID, param.IsStop);
            }

            Dictionary<int, int> dicBefore = new Dictionary<int, int>();
            foreach (var param in this.BeforeList)
            {
                if (param.StepID == 0) continue;
                dicBefore.Add(param.StepID, param.Delay);
            }

            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (var param in this.DevStateList)
            {
                if (param.DevType == 0 || param.DevID == 0) continue;
                dic.Add(param.DevType + "|" + param.DevID, param.DevStateID);
            }
            // viewModel.Prerequisite = JsonConvert.SerializeObject(dicTrainPosition) + ";" + JsonConvert.SerializeObject(dicBefore) + ";" + JsonConvert.SerializeObject(dic);

            if (viewModel.Id == 0)
            {
                int newId = Paper_TestQuestion_TaskDAL.Insert(viewModel.Model);
                if (newId > 0)
                {
                    viewModel.Id = newId;
                    this.DialogResult = true;
                }
            }
            else
                if (Paper_TestQuestion_TaskDAL.Update(viewModel.Model) > 0)
                    this.DialogResult = true;
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //北京科研添加去除事后步骤 add by ljz 2023/6/29
        private void BtnDelete_Click(object sender, RoutedEventArgs e)
        {
            String sql = "update paper_testquestion_task a set a.AfterTask=0 where a.Id=" + this.viewModel.Id + ";";
            //ET.DBCommon.DbHelper.ExecuteDataset(sql);
            //MessageBox.Show("删除成功请刷新试卷");

            this.Close();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tokenSource = new CancellationTokenSource();
            fuzzyQuery = new ListenToFuzzyQueryVoid();
            cancellationToken = tokenSource.Token;
            fuzzyQuery.OnFuzzyQuery += UpdateQueryResult;
            //this.BeforeStepList = TestQuestionTaskStepDAL.SelectBeforeStepListByTask(this.viewModel.TestQuestionTaskID);//先弄个假的

            //zzg
            //if (this.viewModel.Prerequisite.Contains(';'))
            //{
            //    var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.viewModel.Prerequisite.Split(';')[0]);
            //    if (dic != null)
            //    {
            //        foreach (var keyValue in dic)
            //        {
            //            int devTrainID = int.Parse(keyValue.Key.Split('|')[0]);
            //            int devAreaID = int.Parse(keyValue.Key.Split('|')[1]);
            //            bool isStop = bool.Parse(keyValue.Value);
            //            var train = this.TrainList.Find(p => p.DeviceId == devTrainID && p.DeviceTypeId == (int)DeviceTypeEnum.列车);
            //            var area = this.AreaList.Find(p => p.DeviceId == devAreaID && p.DeviceTypeId == (int)DeviceTypeEnum.逻辑区段);
            //            TrainPositionParameter param = new TrainPositionParameter()
            //            {
            //                DevTrainID = devTrainID,
            //                DevAreaID = devAreaID,
            //                DevTrainName = train == null ? "" : train.DeviceName,
            //                DevAreaName = area == null ? "" : area.DeviceName,
            //                IsStop = isStop
            //            };
            //            this.TrainPositionList.Add(param);
            //        }
            //    }
            //    dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.viewModel.Prerequisite.Split(';')[1]);
            //    if (dic != null)
            //    {
            //        foreach (var keyValue in dic)
            //        {
            //            int stepID = int.Parse(keyValue.Key);
            //            int delay = int.Parse(keyValue.Value);
            //            BeforeStepParameter param = new BeforeStepParameter()
            //            {
            //                StepID = stepID,
            //                Delay = delay,
            //                //StepName = stepID == 0 ? "" : this.BeforeStepList.Find(p => p.TestQuestionTaskStepID == stepID).StepDescribe
            //            };
            //            this.BeforeList.Add(param);
            //        }
            //    }
            //    dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.viewModel.Prerequisite.Split(';')[2]);
            //    if (dic != null)
            //    {
            //        foreach (var keyValue in dic)
            //        {
            //            int devType = int.Parse(keyValue.Key.Split('|')[0]);
            //            int devID = int.Parse(keyValue.Key.Split('|')[1]);
            //            int devStateID = int.Parse(keyValue.Value);
            //            var dev = MainWindowNew.DeviceList[devType].Find(p => p.DeviceId == devID && p.DeviceTypeId == devType);
            //            var devState = MainWindowNew.DeviceStateList[devType].Find(p => p.ID == devStateID);
            //            PublicParameter param = new PublicParameter()
            //            {
            //                DevType = devType,
            //                DevID = devID,
            //                DevStateID = devStateID,
            //                DevName = dev == null ? "" : dev.DeviceName,
            //                DevStateName = devState == null ? "" : devState.DeviceStatus,
            //                DeviceList = MainWindowNew.DeviceList.ContainsKey(devType) ? MainWindowNew.DeviceList[devType] : null,
            //                DeviceStateList = MainWindowNew.DeviceStateList.ContainsKey(devType) ? MainWindowNew.DeviceStateList[devType] : null
            //            };
            //            this.DevStateList.Add(param);
            //        }
            //    }
            //}
            //this.DicDevType = DeviceDAL.GetDeviceTypeList()
            //   .ToDictionary(t => t.ID, t => t.TypeName);

            //List<TestQuestionTaskViewModel> TaskList = new List<TestQuestionTaskViewModel>();
            //this.viewModelQuestion.TestQuestionTaskList.ToList().ForEach(p => TaskList.AddRange(p.TestQuestionTaskStepList.ToList().FindAll(s => s.TaskType == (int)TaskType.作业 && s.TestQuestionTaskStepID != viewModel.TestQuestionTaskStepID)));
            foreach (var task in this.viewModelQuestion.TestQuestionTasks)
            {
                TestQuestionTaskList.Add(new TestQuestionTaskViewModel(task));

            }

            this.cmbMutexTask.ItemsSource = TestQuestionTaskList;
            this.cmbAfterTask.ItemsSource = TestQuestionTaskList;


            this.DataContext = this;

            if (this.IsLook)
                TestQuestionEdit.JudgeIsLook(this.LayOut);
            select = Task.Run(() =>
            {
                while (true)
                {
                    if (tokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                    while (IsSelected)
                    {
                        try
                        {
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                if (this.taskKeyText.Text == "")
                                {

                                    this.cmbMutexTask.ItemsSource = TestQuestionTaskList;
                                    this.cmbAfterTask.ItemsSource = TestQuestionTaskList;

                                }
                                else
                                {

                                    fuzzyQuery.KeyText = this.taskKeyText.Text;
                                    this.cmbMutexTask.ItemsSource = tempTaskList;
                                    this.cmbAfterTask.ItemsSource = tempTaskList;

                                }
                            }));
                        }
                        catch (Exception ex)
                        {

                        }
                        Thread.Sleep(1000);

                    }
                }

            }, cancellationToken);
        }

        private void UpdateQueryResult(string KeyText)//模糊搜索任务筛选方法 Add by gy
        {
            tempTaskList = TestQuestionTaskList.Where(o => o.AllDescribe.StartsWith(KeyText) || o.AllDescribe.EndsWith(KeyText) || o.AllDescribe.IndexOf(KeyText) != -1).ToList();
        }
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox combox = sender as ComboBox;
            ContentPresenter cp = (sender as ComboBox).TemplatedParent as ContentPresenter;

            if (cp != null)
            {
                if (combox.Name == "cmbDevType")
                {
                    PublicParameter parameter = cp.Content as PublicParameter;
                    parameter.DevID = 0;
                    parameter.DevName = "";
                    parameter.DevStateID = 0;
                    parameter.DevStateName = "";

                    KeyValuePair<int, string> devType = (KeyValuePair<int, string>)combox.SelectedItem;
                    if (MainWindowNew.DeviceList.ContainsKey(devType.Key))
                    {
                        parameter.DeviceList = MainWindowNew.DeviceList[devType.Key];
                        parameter.DevType = devType.Key;
                    }
                    else
                    {
                        parameter.DeviceList = null;
                    }

                    if (MainWindowNew.DeviceStateList.ContainsKey(devType.Key))
                    {
                        parameter.DeviceStateList = MainWindowNew.DeviceStateList[devType.Key];
                        parameter.DevType = devType.Key;
                    }
                    else
                    {
                        parameter.DeviceStateList = null;
                    }
                }
                else if (combox.Name == "cmbDevTrain")
                {
                    TrainPositionParameter parameter = cp.Content as TrainPositionParameter;
                    var dev = combox.SelectedItem as DeviceModel;
                    parameter.DevTrainName = dev.DeviceName;

                }
                else if (combox.Name == "cmbArea")
                {
                    TrainPositionParameter parameter = cp.Content as TrainPositionParameter;
                    var dev = combox.SelectedItem as DeviceModel;
                    parameter.DevAreaName = dev.DeviceName;

                }
                else if (combox.Name == "cmbStep")
                {
                    BeforeStepParameter parameter = cp.Content as BeforeStepParameter;
                    var dev = combox.SelectedItem as Paper_TestQuestion_Task_StepModel;
                    parameter.StepName = dev.Describes;

                }
                else if (combox.Name == "cmbDevName")
                {
                    if (combox.SelectedItem != null)
                    {
                        PublicParameter parameter = cp.Content as PublicParameter;
                        var dev = combox.SelectedItem as DeviceModel;
                        parameter.DevName = dev.DeviceName;
                    }
                }
                else if (combox.Name == "cmbDevStateName")
                {
                    if (combox.SelectedItem != null)
                    {
                        PublicParameter parameter = cp.Content as PublicParameter;
                        var dev = combox.SelectedItem as Device_StateModel;
                        parameter.DevStateName = dev.DeviceStatus;
                    }
                }
            }
        }

        private void BtnPre_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.DevStateList.Add(new PublicParameter());
                    break;
                case "删除":
                    var para = dgDevState.SelectedItem as PublicParameter;
                    if (para != null)
                    {
                        this.DevStateList.Remove(para);
                    }
                    break;
            }
        }

        private void BtnPosition_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.TrainPositionList.Add(new TrainPositionParameter());
                    break;
                case "删除":
                    var para = dgTrainPosition.SelectedItem as TrainPositionParameter;
                    if (para != null)
                    {
                        this.TrainPositionList.Remove(para);
                    }
                    break;
            }
        }

        private void BtnBefore_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.BeforeList.Add(new BeforeStepParameter());
                    break;
                case "删除":
                    var para = dgBeforeStep.SelectedItem as BeforeStepParameter;
                    if (para != null)
                    {
                        this.BeforeList.Remove(para);
                    }
                    break;
            }
        }

        private void KeyText_GotFocus(object sender, RoutedEventArgs e)
        {
            IsSelected = true;
        }

        private void KeyText_LostFocus(object sender, RoutedEventArgs e)
        {
            IsSelected = false;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            tokenSource.Cancel();//取消筛选的Task
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

        }
    }
}
